package cn.iocoder.yudao.module.promotion.service.promotion;

import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.promotion.controller.admin.promotion.vo.*;
import cn.iocoder.yudao.module.promotion.dal.dataobject.promotion.PromotionDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.promotion.dal.mysql.promotion.PromotionMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.promotion.enums.ErrorCodeConstants.*;

/**
 * 促销 Service 实现类
 *
 * @author 徐煜东
 */
@Service
@Validated
@Slf4j
public class PromotionServiceImpl implements PromotionService {

    @Resource
    private PromotionMapper promotionMapper;

    @Override
    public Long createPromotion(PromotionSaveReqVO createReqVO) {
        // 插入
        PromotionDO promotion = BeanUtils.toBean(createReqVO, PromotionDO.class);
        promotionMapper.insert(promotion);
        // 返回
        return promotion.getId();
    }

    @Override
    public void updatePromotion(PromotionSaveReqVO updateReqVO) {
        // 校验存在
        validatePromotionExists(updateReqVO.getId());
        // 更新
        PromotionDO updateObj = BeanUtils.toBean(updateReqVO, PromotionDO.class);
        promotionMapper.updateById(updateObj);
    }

    @Override
    public void deletePromotion(Long id) {
        // 校验存在
        validatePromotionExists(id);
        // 删除
        promotionMapper.deleteById(id);
    }

    @Override
    public PromotionDO getPromotionByProductId(Long productId) {
        try {
            // 模拟数据库查询耗时 1 秒
            Thread.sleep(1_000); // 单位是毫秒
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // 保持中断状态
            log.error("模拟查询被中断", e);
        }
        log.info("【product service】开始处理 productId = {}, time = {}", productId, System.currentTimeMillis());
        return promotionMapper.selectOne(new LambdaQueryWrapperX<PromotionDO>().eq(PromotionDO::getProductId, productId));

    }

    private void validatePromotionExists(Long id) {
        if (promotionMapper.selectById(id) == null) {
            throw exception(PROMOTION_NOT_EXISTS);
        }
    }

    @Override
    public PromotionDO getPromotion(Long id) {
        return promotionMapper.selectById(id);
    }

    @Override
    public PageResult<PromotionDO> getPromotionPage(PromotionPageReqVO pageReqVO) {
        return promotionMapper.selectPage(pageReqVO);
    }

}
